/**
 * 获取当前日期
 * @param format
 * @returns {string}
 */
function getCurrentDate(shift = 0, format = 'yyyy-MM-dd') {
    let dateItem = new Date();
    dateItem.setTime(new Date().getTime() + shift * 24 * 3600 * 1000);
    let dateSeparator = '-';
    let timeSeparator = ':';
    let year = dateItem.getFullYear();
    let month = dateItem.getMonth() + 1 <= 9 ? `0${dateItem.getMonth() + 1}` : dateItem.getMonth() + 1;
    let day = dateItem.getDate() <= 9 ? `0${dateItem.getDate()}` : dateItem.getDate();
    let hour = dateItem.getHours() <= 9 ? `0${dateItem.getHours()}` : dateItem.getHours();
    let minute = dateItem.getMinutes() <= 9 ? `0${dateItem.getMinutes()}` : dateItem.getMinutes();
    let second = dateItem.getSeconds() <= 9 ? `0${dateItem.getSeconds()}` : dateItem.getSeconds();
    if (format === 'yyyy-MM-dd') {
        return `${year}${dateSeparator}${month}${dateSeparator}${day}`;
    } else if (format === 'yyyy-MM-dd HH:mm:ss') {
        return `${year}${dateSeparator}${month}${dateSeparator}${day} ${hour}${timeSeparator}${minute}${timeSeparator}${second}`;
    } else {
        return `${year}${dateSeparator}${month}${dateSeparator}${day}`;
    }
}

/**
 * 获取配置日期
 * @param format
 * @returns {string}
 */
function getRangeDate(format = 'yyyy-MM-dd') {
    let s = 0;
    if (top !== self) {
        s = $(window.parent.document.body).data('report_date_range') || 0;
    }
    return getCurrentDate(-parseFloat(s.toString()), format);
}

/**
 * 自动生成按钮
 * @param parentEle
 * @param buttonArray
 */
function buttonGen(parentEle, buttonArray = []) {
    let permissions = JSON.parse(localStorage.getItem('XZY_USER_PERMISSIONS')) || [];
    let menuId = $('body').data('menu_id');
    for (let i of buttonArray) {
        if (i.text.indexOf('新增') >= 0) {
            i.disabled = permissions.indexOf(menuId + ':ADD') == -1;
        }
        if (i.text.indexOf('修改') >= 0) {
            i.disabled = permissions.indexOf(menuId + ':MODIFY') == -1;
        }
        if (i.text.indexOf('删除') >= 0) {
            i.disabled = permissions.indexOf(menuId + ':DELETE') == -1;
        }
        if (i.text.indexOf('导出') >= 0) {
            i.disabled = permissions.indexOf(menuId + ':EXPORT') == -1;
        }
        if (i.text.indexOf('打印') >= 0) {
            i.disabled = permissions.indexOf(menuId + ':PRINT') == -1;
        }
        $(parentEle).append(`<a class="easyui-linkbutton" id="${i.id}" style="margin: 5px 1px 5px 5px"/>`);
        $(`#${i.id}`).linkbutton({...i})
    }
}

/**
 * 表单编辑
 * @param ele
 */
function enableFormEdit(ele) {
    $("input[textboxname]", ele).each(function (i, n) {
        $(n).textbox('enable');
    });
    $("input[switchbuttonname]", ele).each(function (i, n) {
        $(n).switchbutton('enable');
    });
    $(".easyui-linkbutton", ele).each(function (i, n) {
        if ($(n).linkbutton() != undefined) $(n).linkbutton('enable');
    });
    $(".easyui-checkbox", ele).each(function (i, n) {
        if ($(n).checkbox() != undefined) $(n).checkbox('enable');
    });
}

/**
 * 表单禁止编辑
 * @param ele
 */
function disableFormEdit(ele) {
    $("input[textboxname]", ele).each(function (i, n) {
        $(n).textbox('disable');
    });
    $("input[switchbuttonname]", ele).each(function (i, n) {
        $(n).switchbutton('disable');
    });
    $(".easyui-linkbutton", ele).each(function (i, n) {
        if ($(n).linkbutton() != undefined) $(n).linkbutton('disable');
    });
    $(".easyui-checkbox", ele).each(function (i, n) {
        if ($(n).checkbox() != undefined) $(n).checkbox('disable');
    });
}

/**
 * 封装序列化表单功能
 */
$.fn.serializeObject = function () {
    let o = {};
    let a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}

/**
 * 计算汇总
 * @param arr
 * @param field
 * @param scale
 * @returns {*}
 */
function calculateSum(arr = [], field, scale = 0) {
    let result = arr.reduce((prev, curr) => {
        prev += parseFloat((curr[field] ? parseFloat(curr[field]).toFixed(scale) : 0));
        return prev;
    }, 0);
    return parseFloat(result || 0).toFixed(scale);
}

/**
 * 将数组去重
 * @param arr
 * @param attribute
 * @returns {[]}
 */
function unique(arr, attribute) {
    let new_arr = [];
    let json_arr = [];
    for (let i = 0; i < arr.length; i++) {
        if (new_arr.indexOf(arr[i][attribute]) == -1) {
            new_arr.push(arr[i][attribute]);
            json_arr.push(arr[i]);
        }
    }
    return json_arr;
}

/**
 * 数组排序
 * @param arr
 * @param oldIndex
 * @param newIndex
 * @returns {*}
 */
function reorder(arr, oldIndex, newIndex) {
    if (oldIndex == newIndex) return arr;
    if (oldIndex > newIndex) {
        arr.splice(newIndex, 0, arr[oldIndex])
        arr.splice(oldIndex + 1, 1);
    } else {
        arr.splice(newIndex, 0, arr[oldIndex]);
        arr.splice(oldIndex - 1, 1);
    }
    return arr;
}

function messagerAlert(msg) {
    $.messager.alert('提示', msg, 'warning');
}

function messagerShow(msg) {
    $.messager.show({title: '提示', msg: msg});
}

function messagerConfirm(msg, fn) {
    $.messager.confirm('提示', msg, fn);
}

(function ($) {
    let cls = 'form-dialog-edit';
    $.formDialog = {
        open: function (option) {
            let columns = option.columns;
            let loadData = option['loadData'];
            let div = $(`<div class="${cls}"></div>`);
            let form = $('<form style="width: 100%;height: 100%;" method="post"></form>')
            for (let i of columns) {
                if (i['editor']) {
                    let options = i.editor.options;
                    let type = i.editor.type;
                    let input = $(`<div class="form-row"><label${i['width'] ? 'style="width=' + i['width'] + '"' : ''}><b>${i.title}：</b></label><input name="${i.field}" class="easyui-${type}"></div>`);
                    if (i['id']) {
                        $(input).find('input').attr('id', i['id']);
                    }
                    $(input).find('input')[i.editor.type](options);
                    form.append(input);
                } else {
                    form.append(`<div class="form-row hidden"><label><b>${i.title}：</b></label><input name="${i.field}"></div>`);
                }
            }
            div.append(form);
            div.appendTo($('body'));
            $(`.${cls}`).dialog({
                iconCls: 'icon-edit',
                width: option['width'] ? option['width'] : 400,
                height: option['height'] ? option['height'] : '99%',
                maxHeight: 900,
                modal: true,
                resizable: true,
                title: option['mode'] ? option['mode'] : '新增',
                closed: false,
                onClose: function () {
                    $(this).dialog('destroy');
                },
                onOpen: option['onOpen'] || function () {
                },
                toolbar: option['toolbar'] || [],
                buttons: option['buttons'] || [{
                    text: option['cancelText'] || '取消',
                    iconCls: option['cancelIconCls'] || 'icon-cancel', handler: option['onCancel']
                }, {
                    text: option['okText'] || '保存',
                    iconCls: option['okIconCls'] || 'icon-save',
                    handler: option['onSave']
                }],
                onBeforeOpen: function () {
                    if (loadData) {
                        $(this).find('form').form('load', loadData);
                    }
                }
            })
        },
        close: function () {
            $(`.${cls}`).dialog('destroy');
        },
        enableEditing: function () {
            let ele = $('.' + cls).find('form').eq(0);
            editingSwitch(true, ele);
        },
        disableEditing: function () {
            let ele = $('.' + cls).find('form').eq(0);
            editingSwitch(false, ele);
        },
        enableBtn: function (arr = []) {
            let ele = $('.' + cls).eq(0);
            $(ele).dialog('panel').find("a[class*='l-btn']").each(function () {
                let btnOpts = $(this).linkbutton('options');
                if (arr.indexOf(btnOpts.text) >= 0) {
                    $(this).linkbutton('enable');
                } else {
                    $(this).linkbutton('disable');
                }
            })
        },
        disableBtn: function (arr = []) {
            let ele = $('.' + cls).eq(0);
            $(ele).dialog('panel').find("a[class*='l-btn']").each(function () {
                let btnOpts = $(this).linkbutton('options');
                if (arr.indexOf(btnOpts.text) >= 0) {
                    $(this).linkbutton('disable');
                } else {
                    $(this).linkbutton('enable');
                }
            })
        },
        getForm: function () {
            return $(`.${cls}`).eq(0).find('form');
        }
    };

    function editingSwitch(flag, ele) {
        $("input[textboxname]", ele).each(function (i, n) {
            $(n).textbox(flag ? 'enable' : 'disable');
        });
        $("input[switchbuttonname]", ele).each(function (i, n) {
            $(n).switchbutton(flag ? 'enable' : 'disable');
        });
        $(".easyui-linkbutton", ele).each(function (i, n) {
            if ($(n).linkbutton() != undefined) $(n).linkbutton(flag ? 'enable' : 'disable');
        });
        $(".easyui-checkbox", ele).each(function (i, n) {
            if ($(n).checkbox() != undefined) $(n).checkbox(flag ? 'enable' : 'disable');
        });
    }
})(jQuery);
(function ($) {
    $.fn.createSimpleDialog = {
        defaultValue: {
            width: 400,
            height: 300,
            columns: [[]],
            data: [],
            url: '',
            queryParams: {},
            resizable: true,
            method: 'GET',
            singleSelect: true,
            onClose: function () {
            },
            onOpen: function () {
            },
            onLoadSuccess: function () {
            },
            onClickRow: function () {
            },
            onDblClickRow: function () {
            },
            onSelect: function () {
            },
            buttons: [],
            toolbar: []
        }
    };
    let defaultValue = $.fn.createSimpleDialog.defaultValue;
    const bodyCls = 'create-simple-dialog';
    // 2021年8月19日 16:59:39 chanchaw 采用UUID，注释上面代码
    // const uuid1 = uuid();
    // const bodyCls = uuid1;
    // console.log('自动创建的对话框UUID：',uuid1);
    const tableId = `${bodyCls}-table`
    $.createSimpleDialog = {
        create: function (opts) {
            let div = $(`
                            <div class="easyui-dialog ${bodyCls}">
                                <table id="${tableId}"></table>
                            </div>
                        `);
            div.appendTo($('body'));
            $(div).dialog({
                width: opts['width'] ? opts.width : defaultValue.width,
                height: opts['height'] ? opts.height : defaultValue.height,
                modal: true,
                title: opts.title,
                onClose: function () {
                    (!opts['onClose'] ? defaultValue.onClose : opts['onClose']).call($(this));
                    $(this).dialog('destroy');
                },
                onOpen: function () {
                    (!opts['onOpen'] ? defaultValue.onOpen : opts['onOpen']).call($(this));
                },
                resizable: opts['resizable'] ? opts.resizable : defaultValue.resizable,
                buttons: opts['buttons'] ? opts.buttons : defaultValue.buttons,
                toolbar: opts['toolbar'] ? opts.toolbar : defaultValue.toolbar,
            });
            $(`#${tableId}`).datagrid({
                url: opts['url'] ? opts.url : defaultValue.url,
                queryParams: opts['queryParams'] ? opts.queryParams : defaultValue.queryParams,
                method: opts['method'] ? opts.method : defaultValue.method,
                data: opts['data'] ? opts.data : defaultValue.data,
                striped: true,
                fitColumns: true,
                fit: true,
                sortable: true,
                columns: opts['columns'] ? opts.columns : defaultValue.columns,
                rownumbers: true,
                remoteSort: false,
                showFooter: true,
                singleSelect: true,
                onSelect: opts['onSelect'] ? opts.onSelect : defaultValue.onSelect,
                onDblClickRow: opts['onDblClickRow'] ? opts.onDblClickRow : defaultValue.onDblClickRow,
                onClickRow: opts['onClickRow'] ? opts.onClickRow : defaultValue.onClickRow,
            })
        },
        destroy: function () {
            console.log($(`.${bodyCls}`))
            $(document).find(`.${bodyCls}`).eq(0).dialog('close');
        },
        getDataGrid: function () {
            return $(`#${tableId}`).length > 0 ? $(`#${tableId}`) : undefined;
        },
        getDialog: function () {
            return $(`.${bodyCls}`).length > 0 ? $(`.${bodyCls}`).eq(0) : undefined;
        }
    }
})(jQuery);
(function ($) {
    var defaultOptions = {
        mode: 'local',
        url: '',
        method: 'GET',
        data: [],
        pageSize: 0,
        totalSize: 0,
        currentPage: 0,
        onClick: (item) => {
        },
        onDblClick: () => {
        },
        onLoadSuccess: () => {
        },
        emptyText: '无数据',
        textField: 'text',
        valueField: 'id',
        closed: false,
        toolbarPosition: 'top',
        btnStyle: 'padding: 5px;',
        queryParams: {}
    }
    $.fn.extend({
        command: function (options, jq) {
            let content = ``;
            $(jq).dialog({
                modal: true,
                width: options.width,
                height: options.height,
                title: options.title,
                iconCls: options.iconCls,
                closed: options.closed,
            });
            if (options.mode === 'local') {
                writeTo(options.data, $(jq).dialog('body'));
            } else {
                $.ajax({
                    url: options.url,
                    data: options.queryParams,
                    type: options.method,
                    dataType: 'json',
                    success: function (data) {
                        writeTo(data, $(jq).dialog('body'));
                    },
                    error: function () {
                    }
                })
            }
        }
    })

    function writeTo(data, target) {
        let div = $(`<div></div>`);
        for (let i = 0, len = data.length; i < len; i++) {
            div.append(`<div style="${options.btnStyle}">
                            <a class="easyui-linkbutton" key="${i}" 
                                    data-value="${data[i][options.valueField]}"
                                    data-options=""
                                    >
                                ${data[i][options.textField]}
                            </a>
                        </div>`);
        }
        $(target).empty();
        div.appendTo($(target));
        $.parser.parse(div);
    }
})(jQuery);
(function ($) {
    $.fn.datagrid.defaults = $.extend({}, $.fn.datagrid.defaults, {
        loader: function (x, y, z) {
            var opts = $(this).datagrid("options");
            if (!opts.url) {
                return false;
            }
            $.ajax({
                type: opts.method,
                url: opts.url,
                data: x,
                traditional: true,
                dataType: "json",
                success: function (data) {
                    y(data);
                },
                error: function () {
                    z.apply(this, arguments);
                }
            });
        }
    });
})(jQuery);
(function ($) {
    $.ajaxSettings.complete = function (xhr, status) {
        setTimeout(function () {
            $.messager.progress('close');
        }, 0)
    }
    $.ajaxSettings.beforeSend = function (xhr, set) {
        if ($('.messager-progress').length <= 0)
            $.messager.progress({title: '提示', text: '请稍候......', interval: 5000});
    }
})(jQuery);

/**
 * 2021年8月19日 15:54:46 chanchaw
 * 获取指定ID的 kendoGrid 的选中行的数据
 * @param gridId
 */
function getKendoGridSelectedRowData(gridId){
    const kendoGrid = $(`#${gridId}`).data("kendoGrid");
    if( !kendoGrid ) return null;
    const selectedRows = kendoGrid.select();
    if( !selectedRows ) return null;

    let ret = [];
    let selected = Array.from(selectedRows);
    selected.forEach(ele => {
        let data = kendoGrid.dataItem(ele);
        ret.push(data);
    })

    return ret;
}


function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}

/**
 * 2021年8月20日 13:21:41 chanchaw
 * 获取 easyui grid 选中行
 */
function getEasyuiGridSelectedRows(gridId){
    return $(`#${gridId}`).datagrid('getSelections');
}

/**
 * 2021年8月20日 13:23:28 chanchaw
 * 获取 easyui grid 所有行
 * @returns {jQuery|*|Array}
 */
function getEasyuiGridAllRows(gridId){
    return $(`#${gridId}`).edatagrid('getRows');
}